--[[
	Jelly Baby Serverside
	Author: Adult
]]--

require( "mysqloo" )

--[[
	You want to define the tables in the init files 
	so it's defined in that specific environment.
]]--

if not admin then
	admin = {}
	-- ConVar data/functions
	admin.cvars    = {}

	-- Database information ONLY.
	admin.database = {}

	-- Rank storage
	admin.ranks = {}

		-- Potato
		admin.ranks.potato = {}

		-- User
		admin.ranks.user = {}

		-- Respected 
		admin.ranks.respected = {}

		-- Donor 
		admin.ranks.donor = {}

		-- Admins 
		admin.ranks.admins = {}

		-- Supers 
		admin.ranks.superadmins = {}

		-- Owners
		admin.ranks.owners = {}
	
		print( "Loading Jelly Baby...")
end

-- This is the library file
include( "admin/modules/sv_admin.lua" )
include( "admin/modules/sh_admin.lua" )

------------------------------------------------------------
--[[ 
			DATABASE INFORMATION.
	I put this up here so it's easier to find.
	If a category does not need to be filled, then
	comment it out.
]]--

local database = file.Read( "addons/jelly-baby/sql/sql_data.txt", true )
local exp = string.Explode( "\n", database )

-- Make sure they filled out the necessary categories
if string.len( database ) > 215 then
	for i=1, #exp do
		local str = exp[i]
		-- If it's not a comment
		if string.sub( str, 1, 1 ) ~= "#" then
			-- If it's being used
			if string.sub( str, -1 ) ~= "_" then
				local str = string.Explode( ":", str )
				if str[1] == "port" then
					admin.database[ str[1] ] = tonumber( str[2] )
				else
					admin.database[ str[1] ] = str[2]
				end
			end
		end
	end
else
	MsgC( Color( 255, 0, 0 ), "sql/sql_data.txt is not setup!" )
end

------------------------------------------------------------

-- Convars, man.
admin.addConVar( "log", 0, FCVAR_SERVER_CAN_EXECUTE, "Log to the database/file." )
admin.addConVar( "usedatabase", 0, FCVAR_SERVER_CAN_EXECUTE, "Use a MySQL Database." ) 
admin.addConVar( "testdatabase", 1, FCVAR_SERVER_CAN_EXECUTE, "Test database when possible." )


--[[ 
	Database stuff, long and boring, just precautionary.
		-- See MySQLOO docs to make sense of the functions
		-- You'll probably need to know SQL too :P
]]--

-- Define the database
local db = admin.database 
admin.db = mysqloo.connect( db.host, db.username, db.password, db.database, db.port )

-- Save your fingers a bit
local db = admin.db 

-- When the database connects, run a test.
function db:onConnected()
	print( "MySQL Database connected")

	-- MySQL uses the Think hook, and that doesn't start running until a player joins
	-- So we can't test the Database yet. :c
	if #player.GetAll() < 1 then
		print( "Can not test database, must wait until someone joins the game." )

		return 
	end

	print( "Test query running...")

	local q = self:query( "SELECT Rank FROM UserData")

	function q:onSuccess( data )
		print( "Test query successful!" )
	end
	
	function q:onError( err, sql )
		print( "Test query failed! Database not setup!" )
		print( "Please run the database_setup.sql to set up the database!" )

		admin.disconnectDatabase()
	end
end

-- On the off chance it fails.
function db:onConnectionFailed( err )
	print( "Connection to MySQL database failed!" )
	print( "Error: ", err )
end

db:connect()
-------------- End Database Loading ---------------------

-- We want to check if this player has joined before, if they haven't set up an SQL entry for em
local function onFirstSpawn( ply )
	local q = db:query( "SELECT FROM UserData WHERE SteamID='" .. ply:SteamID() .. "'" )

	function q:onSuccess( data )
		ply:ChatPrint( "Your MySQL Data has been loaded.")
		ply:ChatPrint( "Last Known Name: " .. data[ LastName ] )
		ply:ChatPrint( "SteamID: " .. data[ SteamID ] )
		ply:ChatPrint( "Rank: " .. data[ Rank ] )
		ply:ChatPrint( "Playtime: " .. data[ PlayTime ] )

		local index = ply:SteamID()
		local rankname = string.lower( data[ Rank ] )
		ply.rank = rankname
		admin.ranks[ rankname ] = ply
	end
	
	function q:onError( err, sql )
		ply:ChatPrint( "Your MySQL Data could not be loaded." )
		ply:ChatPrint( "This should only happen when the MySQL database hasn't been loaded, or it is your first time joining." )
		ply:ChatPrint( "If neither of those are true, contact your server administrator." )

		admin.newUserData( ply:SteamID(), ply:Name(), "user", 0, CurTime() )
	end

end

hook.Add( "PlayerInitialSpawn", "CheckUserData", onFirstSpawn )


-- Test the database pls.
local function testDatabase()
	admin.testDatabase()

	hook.Remove( "PlayerInitialSpawn", "TestDatabase" )
end

if GetConVar( "jb_testdatabase" ):GetInt() == 1 then
	hook.Add( "PlayerInitialSpawn", "TestDatabase", testDatabase )
end


-------------------------------------------------------------------
-- dun.
print( "Jelly Baby finished loading." )

-- Now to the fun stuff...

local function playerSay( ply, text, public )
	local args = string.Explode( " ", text )

	-- Identifier for commands ( saying "/kick" )
	local first = string.sub( args[1], 1, 1 )

	if first == "/" then
		-- Change first to the first word without the identifier
		first = string.sub( args[1], 2 )

	end
end